package com.example.musictutor.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;

import android.widget.Toast;
import com.example.musictutor.R;
import com.example.musictutor.conf.Constants;
import com.example.musictutor.domain.Note;
import com.example.musictutor.domain.ProgressHistory;
import com.example.musictutor.domain.Song;
import com.example.musictutor.domain.SongNote;
import com.example.musictutor.factories.ProgressHistoryFactory;
import com.example.musictutor.factories.SongNoteFactory;
import com.example.musictutor.fragments.HelpDialog;
import com.example.musictutor.fragments.SettingsDialog;
import com.example.musictutor.repository.facade.impl.NoteDAOFacade;
import com.example.musictutor.repository.facade.impl.ProgressHistoryDAOFacade;
import com.example.musictutor.repository.facade.impl.SongDAOFacade;

public class AppHome extends Activity implements View.OnClickListener{

    private Context context = this;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_app_home);
		
		// Used to destroy database, so that it can be recreated
		deleteDatabase(Constants.DATABASE_NAME);
		
		populateNotes();
		populateSongs();
		
        ImageButton lastPlayed = (ImageButton)findViewById(R.id.lastPlayed);
        ImageButton levelSelect = (ImageButton)findViewById(R.id.levelSelect);
        ImageButton viewProgress = (ImageButton)findViewById(R.id.viewProgress);
        ImageButton aboutUs = (ImageButton)findViewById(R.id.aboutUs);

        lastPlayed.setOnClickListener(this);
        levelSelect.setOnClickListener(this);
        viewProgress.setOnClickListener(this);
        aboutUs.setOnClickListener(this);

	}


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.app_home_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_settings:
                //call settings dialog
                SettingsDialog settingsDialog = new SettingsDialog();
                settingsDialog.show(getFragmentManager(),"Dialog App Settings");
                return true;
            case R.id.action_help:
                //call help dialog
                HelpDialog helpDialog = new HelpDialog();
                helpDialog.show(getFragmentManager(),"Dialog App Help");
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onClick(View v) {
        v.startAnimation(AnimationUtils.loadAnimation(context, R.anim.image_click));
        switch(v.getId()){
            case R.id.lastPlayed:
            	
            	// Get list of all songs
            	SongDAOFacade dao = new SongDAOFacade(this);
            	List<Song> songList = dao.getEntities();
            	
            	long songId = -1;
            	
            	// For the sake of not enought time, the first level found still locked should be the last played level
            	for(Song s :  songList) {
            		if(!s.isUnlocked()) {
            			songId = s.getId();
            			break;
            		}
            	}
            	
            	// When all songs have been unlocked, for now just set id to any song
            	if(songId == -1)
            		songId = songList.get(1).getId();
            	
            	songId = songList.get(2).getId();
            	
            	Intent intent = new Intent(this, PlaySongActivity.class);
            	intent.putExtra("songId", songId);
                startActivity(intent);
                break;
                
            case R.id.levelSelect:
                startActivity(new Intent(context,LevelSelect.class));
                break;
            case R.id.viewProgress:
                startActivity(new Intent(context,ProgressLevelSelect.class));
                break;
            case R.id.aboutUs:
                startActivity(new Intent(context,AboutUs.class));
                break;
            default:;
        }
    }
    
    private void populateNotes() {
    	NoteDAOFacade dao = new NoteDAOFacade(this);
    	//dao.deleteAll();
    	List<Note> noteList = dao.getEntities();
    	
    	if(noteList.size() > 0) {
    		for(Note note : noteList) {
    			note.setResourceId(getResourceId(note.getName()));
    			dao.updateEntity(note);
    		}
    	}
    	else {
    		String[] notes = { "C", "D", "E", "F", "G", "A", "B" };
    		Note note = null;
			for(int i=0;i<notes.length;i++) {
				note = new Note(notes[i], getResourceId(notes[i]));
				dao.createEntity(note);
			}
    	}
    }
    
    private void populateSongs() {
    	SongDAOFacade dao = new SongDAOFacade(this);
    	//dao.deleteAll();
    	
    	List<Song> songList = dao.getEntities();
    	
    	if(songList.size() == 0) {
            ProgressHistoryDAOFacade progressHistoryDAOFacade = new ProgressHistoryDAOFacade(this);

    		NoteDAOFacade noteDao = new NoteDAOFacade(this);
        	List<Note> noteList = noteDao.getEntities();
        	
    		// Song 1
    		List<SongNote> songNoteList = new ArrayList<SongNote>();

    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("C", noteList), 0, 999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("D", noteList), 1000, 1999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("E", noteList), 2000, 2999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("C", noteList), 3000, 3999));

    		Song song = new Song();
    		song.setName("Song 1");
    		song.setNotes(songNoteList);
    		song.setTempo(120);
    		song.setHighscore(0);
    		song.setUnlocked(false);
    		
    		long easySongId = dao.createEntity(song);

            //create initial Progress History this is a hackish way, since were not implementing more levels
            HashMap<String,Integer> values = new HashMap<String, Integer>();
            values.put("amountOfAttempts",0);
            values.put("amountPassed",0);
            values.put("amountFailed",0);
            values.put("level",1);
            values.put("songId",(int)easySongId);
            Log.d(Constants.LOG_TAG, "SOng Id" +easySongId);

            ProgressHistory progressEasySong = ProgressHistoryFactory.createProgressHistory(1, values);

            long easyPHId = progressHistoryDAOFacade.createEntity(progressEasySong);

    		// Song 2
    		songNoteList = new ArrayList<SongNote>();

    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("C", noteList), 0, 999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("E", noteList), 1000, 1499));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("E", noteList), 1500, 1999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("F", noteList), 2000, 2499));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("F", noteList), 2500, 2999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("C", noteList), 3000, 3999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("E", noteList), 3000, 3999));

    		song = new Song();
    		song.setName("Song 2");
    		song.setNotes(songNoteList);
    		song.setTempo(120);
    		song.setHighscore(0);
    		song.setUnlocked(false);

            long mediumSongId = dao.createEntity(song);
            values.clear();
            values = new HashMap<String, Integer>();
            values.put("amountOfAttempts",0);
            values.put("amountPassed",0);
            values.put("amountFailed",0);
            values.put("level",1);
            values.put("songId",(int)mediumSongId);
            ProgressHistory progressMediumSong = ProgressHistoryFactory.createProgressHistory(2,values);

            long medPHId = progressHistoryDAOFacade.createEntity(progressMediumSong);
    		// Song 3
    		songNoteList = new ArrayList<SongNote>();

    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("C", noteList), 0, 999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("E", noteList), 0, 999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("G", noteList), 0, 999));
    		
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("E", noteList), 1000, 1999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("G", noteList), 1000, 1999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("B", noteList), 1000, 1999));
    		
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("F", noteList), 2000, 2499));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("A", noteList), 2000, 2499));
    		
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("F", noteList), 2500, 2999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("A", noteList), 2500, 2999));
    		
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("E", noteList), 3000, 3999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("G", noteList), 3000, 3999));
    		songNoteList.add(SongNoteFactory.createSongNote(0, 0, getNote("B", noteList), 3000, 3999));

    		song = new Song();
    		song.setName("Song 3");
    		song.setNotes(songNoteList);
    		song.setTempo(120);
    		song.setHighscore(0);
    		song.setUnlocked(false);

            long difficultSongId = dao.createEntity(song);

            values.clear();
            values = new HashMap<String, Integer>();
            values.put("amountOfAttempts",0);
            values.put("amountPassed",0);
            values.put("amountFailed",0);
            values.put("level",1);
            values.put("songId",(int)difficultSongId);

            ProgressHistory progressDifficultSong = ProgressHistoryFactory.createProgressHistory(3,values);

            long diffPHId =  progressHistoryDAOFacade.createEntity(progressDifficultSong);
    	}
    }
    
    private int getResourceId(String note) {
    	if(note.equalsIgnoreCase("C"))
    		return R.raw.c_note;
    	else if(note.equalsIgnoreCase("D"))
    		return R.raw.d_note;
		else if(note.equalsIgnoreCase("E"))
			return R.raw.e_note;
		else if(note.equalsIgnoreCase("F"))
			return R.raw.f_note;
		else if(note.equalsIgnoreCase("G"))
			return R.raw.g_note;
		else if(note.equalsIgnoreCase("A"))
			return R.raw.a_note;
		else if(note.equalsIgnoreCase("B"))
			return R.raw.b_note;
    	
    	return 0;
    }
    
    private Note getNote(String name, List<Note> list) {
    	for(Note n : list) {
    		if(n.getName().equalsIgnoreCase(name))
    			return n;
    	}
    	
    	return null;
    }
}






